package com.phpxiu.app.upload;

import android.os.Handler;
import android.os.Message;

import com.phpxiu.app.utils.KKYUtil;
import com.tencent.cos.model.COSRequest;
import com.tencent.cos.model.COSResult;
import com.tencent.cos.model.PutObjectResult;
import com.tencent.cos.task.listener.IUploadTaskListener;

/**
 * @file
 * @brief 文件上传UI回调
 * @author 吴金洲
 * @note  基于腾讯云对象存储4.0+服务实现
 */
public abstract class UploadUIHandler extends Handler implements IUploadTaskListener {

    private final static int UPLOAD_CANCEL=-0x500;
    private final static int UPLOAD_SUCCESS=-0x501;
    private final static int UPLOAD_FAILED=-0x502;

    @Override
    public void onProgress(COSRequest cosRequest, long progress, long total) {
        KKYUtil.log("上传进度" + progress + "/" + total);
    }

    @Override
    public void onCancel(COSRequest cosRequest, COSResult cosResult) {
        sendEmptyMessage(UPLOAD_CANCEL);
    }

    @Override
    public void onSuccess(COSRequest cosRequest, COSResult cosResult) {
        Message message=obtainMessage();
        message.what=UPLOAD_SUCCESS;
        PutObjectResult result = (PutObjectResult) cosResult;
        result.source_url=cosRequest.getCosPath();
        message.obj=result;
        sendMessage(message);
    }

    @Override
    public void onFailed(COSRequest cosRequest, COSResult cosResult) {
        Message message=obtainMessage();
        message.what=UPLOAD_FAILED;
        message.obj=cosResult;
        sendMessage(message);
    }

    @Override
    public void handleMessage(Message msg) {
        switch (msg.what){
            case UPLOAD_CANCEL:
                onUploadCancel();
                break;
            case UPLOAD_SUCCESS:
                PutObjectResult result = (PutObjectResult) msg.obj;
                KKYUtil.log("URL_A:"+result.access_url);
                KKYUtil.log("URL_S:"+result.source_url);
                KKYUtil.log("URL_S:"+result.preview_url);
                onUploadSuccess(result.source_url,result.access_url);
                break;
            case UPLOAD_FAILED:
                COSResult cosResult=(COSResult)msg.obj;
                onUploadFailed(cosResult.code,cosResult.msg);
                break;
        }
    }

    /**
     * @param key 保存到本地业务服务器的信息：/分类目录/文件名.jpg
     * @param url 腾讯服务器返回的完整url包含域名，用于显示图片等
     */
    public abstract void onUploadSuccess(String key,String url);

    /**
     * 取消上传
     */
    public abstract void onUploadCancel();

    /**
     * 上传失败
     * @param errCode 错误码
     * @param errMsg 错误描述
     */
    public abstract void onUploadFailed(int errCode,String errMsg);
}
